<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import {injectGlobalStyles} from "@/zdpui/util/style.js";

const props = defineProps({
  size: {
    type: Number,
    default: 30,
  },
})

const canvas = ref(null)
const backgroundContainer = ref(null)
let ctx
let bubbles = []
let animationFrameId
let gradient

class Bubble {
  constructor() {
    this.x = Math.random() * window.innerWidth
    this.y = window.innerHeight
    this.radius = Math.random() * 20 + 5
    this.speed = Math.random() * 2 + 1
  }

  update() {
    this.y -= this.speed
  }

  draw() {
    ctx.beginPath()
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2)
    ctx.fillStyle = 'rgba(255, 255, 255, 0.6)'
    ctx.fill()
  }
}

const init = () => {
  ctx = canvas.value.getContext('2d')
  gradient = ctx.createLinearGradient(0, 0, 0, canvas.value.height)
  gradient.addColorStop(0, '#e0f7fa')
  gradient.addColorStop(1, '#80deea')
  ctx.fillStyle = gradient
  ctx.fillRect(0, 0, canvas.value.width, canvas.value.height)

  for (let i = 0; i < props.size; i++) {
    bubbles.push(new Bubble())
  }
}

const animate = () => {
  // 画背景
  ctx.fillStyle = gradient
  ctx.fillRect(0, 0, canvas.value.width, canvas.value.height)

  // 更新和绘制泡泡
  bubbles.forEach(bubble => {
    bubble.update()
    bubble.draw()
  })

  // 移除超出屏幕的泡泡，并补充新的泡泡
  bubbles = bubbles.filter(bubble => bubble.y - bubble.radius > -canvas.value.height)
  while (bubbles.length < props.size) {
    bubbles.push(new Bubble())
  }

  // 继续动画
  animationFrameId = requestAnimationFrame(animate)
}

onMounted(() => {
  canvas.value.width = window.innerWidth
  canvas.value.height = window.innerHeight
  init()
  animate()
  window.addEventListener('resize', handleResize)
  injectGlobalStyles()
})

onUnmounted(() => {
  cancelAnimationFrame(animationFrameId)
  window.removeEventListener('resize', handleResize)
})

const handleResize = () => {
  canvas.value.width = window.innerWidth
  canvas.value.height = window.innerHeight
  gradient = ctx.createLinearGradient(0, 0, 0, canvas.value.height)
  gradient.addColorStop(0, '#e0f7fa')
  gradient.addColorStop(1, '#80deea')
  ctx.fillStyle = gradient
  ctx.fillRect(0, 0, canvas.value.width, canvas.value.height)
}
</script>

<template>
  <div class="canvas-background" ref="backgroundContainer">
    <canvas ref="canvas"></canvas>
    <div class="content">
      <slot></slot>
    </div>
  </div>
</template>


<style scoped>
.canvas-background {
  position: relative;
  width: 100%;
  height: 100vh;
}

canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.content {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1;
}
</style>